package com.hjm.friend.service.user.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjm.api.RemoteJudgeService;
import com.hjm.api.domain.JudgeResult;
import com.hjm.api.domain.JudgeSubmitDTO;
import com.hjm.api.domain.UserExeResult;
import com.hjm.api.domain.UserQuestionResultVO;
import com.hjm.common.core.constants.Constants;
import com.hjm.common.core.domain.Result;
import com.hjm.common.core.enums.*;
import com.hjm.common.core.utils.JsonUtils;
import com.hjm.common.core.utils.ThreadLocalUtils;
import com.hjm.friend.domain.question.Question;
import com.hjm.friend.domain.question.QuestionCase;
import com.hjm.friend.domain.question.QuestionES;
import com.hjm.friend.elasticsearch.QuestionRepository;
import com.hjm.friend.mapper.question.QuestionMapper;
import com.hjm.friend.rabbitmq.JudgeProducer;
import com.hjm.security.exception.ServiceException;
import com.hjm.friend.domain.user.UserSubmit;
import com.hjm.friend.domain.user.dto.UserSubmitDTO;
import com.hjm.friend.mapper.user.UserSubmitMapper;
import com.hjm.friend.service.user.UserSubmitService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.CoderResult;
import java.util.List;


@Service
public class UserSubmitServiceImpl extends ServiceImpl<UserSubmitMapper, UserSubmit> implements UserSubmitService {

    @Autowired
    QuestionRepository questionRepository;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    RemoteJudgeService remoteJudgeService;

    @Autowired
    JudgeProducer judgeProducer;

    @Autowired
    private UserSubmitMapper userSubmitMapper;


    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        // 现根据语言进行判断 怎样进行逻辑处理
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)) {
            // 按照 java 逻辑进行处理
            JudgeSubmitDTO judgeSubmit = assembleJudgeSubmit(userSubmitDTO);
            // 远程调用 java 判题服务
            return remoteJudgeService.doJudgeJavaCode(judgeSubmit);
        }

        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_TYPE);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        // 现根据语言进行判断 怎样进行逻辑处理
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)) {
            // 按照 java 逻辑进行处理
            JudgeSubmitDTO judgeSubmit = assembleJudgeSubmit(userSubmitDTO);
            // 使用 rabbitmq 进行消息的发送
            judgeProducer.produceMsg(judgeSubmit);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_TYPE);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId,String currentTime) {
        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        // 从 数据库中获取 题目结果
        UserSubmit userSubmit = userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO userQuestionResultVO = new UserQuestionResultVO();
        if(userSubmit != null) {
            userQuestionResultVO.setPass(userSubmit.getPass());
            if(StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
                userQuestionResultVO.setResults(JsonUtils.toList(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
            userQuestionResultVO.setErrorMsg(userSubmit.getErrorMessage());
        }else{
            userQuestionResultVO.setPass(QuestResultCode.IN_JUDGE.getValue());
        }
        return userQuestionResultVO;
    }

    // 根据 questionId 组装 judgeSubmit 信息
    private JudgeSubmitDTO assembleJudgeSubmit(UserSubmitDTO submitDTO) {
        // 先去 es 中进行数据查询
        Long questionId = submitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);

        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if(questionES != null) {
            // 题目存在
            BeanUtils.copyProperties(questionES, judgeSubmitDTO);
        }else{
            // 题目不存在 , 从数据库中进行题目的获取
            Question question = questionMapper.selectById(questionId);
            BeanUtils.copyProperties(question, judgeSubmitDTO);
            // 同步到 es 中
            questionES = new QuestionES();
            BeanUtils.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }

        // 到这里 题目基本信息都已经获取到 存储再judgeSubmitDTO中
        judgeSubmitDTO.setUserId(ThreadLocalUtils.get(Constants.USER_ID, Long.class));
        judgeSubmitDTO.setExamId(submitDTO.getExamId());
        judgeSubmitDTO.setProgramType(submitDTO.getProgramType());
        // 组装 userCode , 方便等会可以 运行
        judgeSubmitDTO.setUserCode(codeConnect(submitDTO.getUserCode(),questionES.getMainFunc()));

        List<QuestionCase> questionCaseList = JsonUtils.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> input = questionCaseList.stream().map(QuestionCase::getInput).toList();
        List<String> output = questionCaseList.stream().map(QuestionCase::getOutput).toList();

        judgeSubmitDTO.setInputList(input);
        judgeSubmitDTO.setOutputList(output);

        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFunc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFunc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }


}
